package ldz.Show;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import ldz.User.*;
import ldz.lian.*;
import xxh.BackgroundPanel;
import xxh.MainWindow;


public class LoginWindow extends JFrame {
    private JTextField readerIdField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton switchToAdminButton;
    private JButton registrationButton;

    public LoginWindow() {
        // 设置窗口标题为"图书管理系统"
        setTitle("图书管理系统");
        // 设置窗口大小，这里适当扩大窗口尺寸，可根据实际需求进一步调整
        setSize(400, 300);
        // 设置窗口关闭操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建并设置窗口的标题面板，用于显示主标题和副标题
        initTitlePanel();

        // 初始化组件
        initComponents();

        // 显示窗口
        setVisible(true);
    }

    private void initTitlePanel() {
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JLabel mainTitleLabel = new JLabel("图书管理系统");
        mainTitleLabel.setFont(new Font("宋体", Font.BOLD, 20));
        JLabel subTitleLabel = new JLabel("用户登录");
        subTitleLabel.setFont(new Font("宋体", Font.PLAIN, 16));
        titlePanel.add(mainTitleLabel);
        titlePanel.add(subTitleLabel);
        add(titlePanel, BorderLayout.NORTH);
    }

    private void initComponents() {
        JPanel mainPanel = new JPanel(new BorderLayout());

        // 用于放置读者编号和密码输入相关组件的面板，使用GridBagLayout布局实现更灵活的定位

        //xxh改
        BackgroundPanel inputPanel = new BackgroundPanel("src/xxh/img/bk.jpg",300,150);
        inputPanel.setLayout(new GridBagLayout());
       // JPanel inputPanel = new JPanel(new GridBagLayout());
        //xxh
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5); // 设置组件之间的间距

        // 添加读者编号相关组件
        gbc.gridx = 0;
        gbc.gridy = 0;
        inputPanel.add(new JLabel("读者编号："), gbc);
        gbc.gridx = 1;
        readerIdField = new JTextField(15); // 设置合适的文本框宽度
        inputPanel.add(readerIdField, gbc);

        // 添加密码相关组件
        gbc.gridx = 0;
        gbc.gridy = 1;
        inputPanel.add(new JLabel("密码："), gbc);
        gbc.gridx = 1;
        passwordField = new JPasswordField(15); // 设置合适的文本框宽度
        inputPanel.add(passwordField, gbc);

        mainPanel.add(inputPanel, BorderLayout.CENTER);

        // 添加登录按钮、管理员登录按钮和注册按钮的面板，使用FlowLayout布局，并设置水平间距等
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));

        // 添加注册按钮
        registrationButton = new JButton("注册");
        registrationButton.setFont(new Font("宋体", Font.PLAIN, 10));
        registrationButton.setPreferredSize(new Dimension(60, 20));
        registrationButton.addActionListener(new RegistrationButtonListener());
        buttonPanel.add(registrationButton);

        // 添加登录按钮
        loginButton = new JButton("登录");
        loginButton.setFont(new Font("宋体", Font.BOLD, 14));  // 设置较大字体使其更突出
        loginButton.setPreferredSize(new Dimension(80, 30));  // 设置较大尺寸
        loginButton.addActionListener(new LoginButtonListener());
        buttonPanel.add(loginButton);

        // 添加切换到管理员登录页面按钮
        switchToAdminButton = new JButton("管理员登录");
        switchToAdminButton.setFont(new Font("宋体", Font.PLAIN, 12)); // 设置较小的字体
        switchToAdminButton.setPreferredSize(new Dimension(100, 20)); // 设置较小的尺寸
        switchToAdminButton.addActionListener(new SwitchToAdminButtonListener());
        buttonPanel.add(switchToAdminButton);

        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private class LoginButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String readerId = readerIdField.getText();
            char[] passwordChars = passwordField.getPassword();
            String password = new String(passwordChars);

            try {
                // 使用DBUtil获取连接
                Connection connection = DBUtil.getConnection();

                // 准备查询语句，按照正确的字段名Uno和Upassword来编写
                String sql = "SELECT * FROM user WHERE Uno =? AND Upassword =?";
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, readerId);
                preparedStatement.setString(2, password);

                // 执行查询
                ResultSet resultSet = preparedStatement.executeQuery();

                if (resultSet.next()) {
                    // 从结果集中构建User对象（根据实际表结构完善赋值操作）
                    User user = new User();
                    user.setUno(resultSet.getString("Uno"));
                    user.setUname(resultSet.getString("Uname"));
                    user.setUsex(resultSet.getString("Usex"));
                    user.setUpassword(resultSet.getString("Upassword"));
                    user.setUtel(resultSet.getString("Utel"));
                    user.setUemail(resultSet.getString("Uemail"));
                    JOptionPane.showMessageDialog(LoginWindow.this, "登录成功！");
                    MainWindow mainWindow = new MainWindow(user.getUno());
                    mainWindow.setLocationRelativeTo(null);
                    mainWindow.setVisible(true);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(LoginWindow.this, "读者编号或密码错误，请重新输入。");
                }

                // 关闭资源
                resultSet.close();
                preparedStatement.close();
                connection.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(LoginWindow.this, "数据库连接错误，请检查！");
            }
        }
    }

    private class SwitchToAdminButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 关闭当前用户登录窗口
            dispose();
            // 打开管理员登录窗口
            AdminLoginWindow adlow = new AdminLoginWindow();
            adlow.setLocationRelativeTo(null);
            adlow.setVisible(true);

        }
    }

    private class RegistrationButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 关闭当前登录窗口
            dispose();
            // 打开注册用户页面
            RegistrationWindow registrationWindow =new RegistrationWindow();
            registrationWindow.setLocationRelativeTo(null);
            registrationWindow.setVisible(true);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new LoginWindow();
        });
    }
}